import React from 'react'
import {Row, Col, Button, Table, Select, Input, Avatar, Modal, message} from 'antd'
import Model from "./Model"
// import { UserOutlined } from '@ant-design/icons';
import '../styles.css'
import api from "../../../api/api";
import axios from 'axios';

const {Search} = Input;
const {Option} = Select;

class MaterialMaintenance extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            modelData: {
                title: "物资管理",
                visible: false,
                type: 1,//新增物资:1,编辑: 2
                gridList: {}
            },
            data: [],
            //companyId:0,
            companyId: undefined,
            mmName: '',
            pageNum: 1,
            pageSize: 10,
            total: 0
        };
    }

    columns = [
        {
            title: 'ID',
            dataIndex: 'meterialId',
            key: 'meterialId',
            width: '10%'
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            width: '10%'
        },
        {
            title: '名称',
            dataIndex: 'meterialName',
            width: '20%',
            key: 'meterialName'
        },
        {
            title: '所属公司',
            dataIndex: 'companyName',
            width: '20%',
            key: 'companyName'
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            width: '20%',
            key: 'createTime'
        },
        {
            title: '操作',
            dataIndex: 'option',
            width: '20%',
            key: 'option',
            render: (text, record, index) => {
                return (
                    <span>
            <a className="optionMargin" onClick={() => this.onClickEdit(record)}>编辑</a>
            <a className="optionMargin" onClick={() => this.onClickDelete(record.meterialId)}>删除</a>
          </span>
                )
            }
        }
    ];

    componentDidMount() {
        console.log("赋值");
        this.getCompanySelect();
        this.getMeterialTypeList();
    }

    getMeterialTypeList() {
        var that = this;
        axios.post(api.api_URL + "/admin/meterialtype/getAllMeterialTypeByParam?pageNum=" + this.state.pageNum + "&pageSize=" + this.state.pageSize, {
            "companyId": that.state.companyId,
            "orgCode": localStorage.getItem("orgCode"),
            "meterialName": that.state.mmName,
        }, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            console.log(res.data)
            if (res.data.code != 1) {
                message.error({content: "加载失败，请重新尝试 ！"})
                return;
            }
            let totalSize = res.data.data.list.totalSize;
            const dataList = [];
            for (let i = 0; i < res.data.data.list.content.length; i++) {
                let resContent = res.data.data.list.content[i];
                const content = {};
                content.key = (i + 1);
                content.meterialId = resContent.meterialId;
                content.type = resContent.type;
                content.meterialName = resContent.meterialName;
                content.companyName = resContent.companyName;
                content.companyId = resContent.companyId;
                content.createTime = resContent.createTime;
                dataList[i] = content;
            }
            that.setState({
                data: dataList,
                total: totalSize
            })
        }).catch(function (err) {
            message.error({content: "加载失败，请重新尝试！"})

            console.log(err);
        });
    }

    onRef = (ref) => {
        this.child = ref
    }

//分页
    onBaseClick(current, pageSize) {
        this.setState({
            pageNum: current,
            pageSize: pageSize
        }, () => {
            this.getMeterialTypeList()
        });

    }

//编辑
    onClickEdit(item) {
        this.setState({
            modelData: {
                title: "编辑管理员",
                type: 2,
                visible: true,
                gridList: item
            }
        }, () => {
            this.child.initEditData()
        });
    }

//删除
    onClickDelete(item) {
        let that = this;
        let configModel = Modal.confirm({
            title: '删除',
            content: '是否确认删除？',
            onOk: (values) => {
                return new Promise((res, rej) => {
                    let url = api.api_URL + "/admin/meterialtype/removeMeterialType?meterialTypeId=" + item;
                    axios({
                        method: 'POST',
                        url: url,
                        headers: {
                            "Authorization": localStorage.getItem('token'),
                            "Content-Type": "application/json;charset=UTF-8"
                        },
                    }).then(function (response) {
                        message.success({content: "删除成功！"})
                        that.getMeterialTypeList()
                        configModel.destroy();
                    })
                        .catch(function (error) {
                            message.error({content: "删除失败，请重新尝试！"})

                            console.log(error);
                        })
                }).catch((e) => console.warn(e));
            },
            onCancel() {
            },
        })
    }

    addmaterial() {
        console.info("新增物资");
        this.setState({
            modelData: {
                title: "新增物资",
                type: 1,
                visible: true
            }
        }, () => {
            this.child.clearData()
        })
        console.info("this.state====", this.state);
    }

    onclickSearch() {
        console.info("搜索");
        this.getMeterialTypeList();
    }

    onclickReset() {
        console.info("重置");
        this.setState({
            companyId: undefined,
            mmName: '',
        }, () => {
            this.getMeterialTypeList()
        });
        console.log(this.props)
    }

    handleOk = e => {
        console.log(e);
        this.setState({
            modelData: {
                visible: false
            }
        });
    };

    handleCancel = e => {
        console.log(e);
        this.setState({
            modelData: {
                visible: false
            }
        }, () => {
            this.refresh()
        });
    };

    refresh() {
        this.getMeterialTypeList()
    }

    //选择公司
    companyChange = (value) => {
        console.info("value=====", value);
        this.setState({
            companyId: value
        })
    }
    //获取公司下拉框值
    factorySelect = [];

    getCompanySelect() {
        this.factorySelect = [];
        let that = this;
        let dataList = [];
        let url;
        url = api.api_URL + "/admin/factory/queryFactoryInfoForSelect?orgCode=" + localStorage.getItem('orgCode');
        axios.get(url, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            if (res.data.code != 1) {
                alert(res.data.msg);
                return;
            }
            let factoryInfoList = res.data.data.factoryInfoList;
            if (factoryInfoList.length <= 0) {
                console.log("没有公司数据")
                return;
            }
            for (let i = 0; i < factoryInfoList.length; i++) {
                let facData = factoryInfoList[i];
                const data = {};
                data.key = facData.factoryId;
                data.label = facData.name;
                dataList[i] = data;
            }
            for (let i = 0; i < dataList.length; i++) {
                that.factorySelect.push(<Option key={dataList[i].key}>{dataList[i].label}</Option>);
            }
        }).catch(function (err) {
            console.log(err);
        })

    }

    inputChange = (e) => {
        this.setState({
            mmName: e.target.value
        })
    }

    exportData = () => {
        let that = this;
        let url = api.api_URL + "/admin/meterialtype/exportAllMeterialType";
        let data = {
            "companyId": that.state.companyId,
            "orgCode": localStorage.getItem("orgCode"),
            "meterialName": that.state.mmName
        }
        that.exportFile(url, data)

    }

    exportFile(url, data) {
        axios({
            method: 'post',
            url: url,
            data: data,
            responseType: 'blob'
        }).then((res) => {
            const content = res.data;
            const blob = new Blob([content]);
            const fileName = "物资信息表.xls";
            const selfURL = window[window.webkitURL ? 'webkitURL' : 'URL'];
            let elink = document.createElement('a');
            if ('download' in elink) {
                elink.download = fileName;
                elink.style.display = 'none';
                elink.href = selfURL['createObjectURL'](blob);
                document.body.appendChild(elink);

                // 触发链接
                elink.click();
                selfURL.revokeObjectURL(elink.href);
                document.body.removeChild(elink)
            } else {
                navigator.msSaveBlob(blob, fileName);
            }
        })
    }

    render() {
        console.info("this.props.match===", this.props);
        return (
            <div className="girdBg">
                <Row className="searchBox">
                    <Col span={18}>
                        <Select showSearch={true} optionFilterProp="children" placeholder="请选择公司" style={{width: 200}}
                                onChange={this.companyChange} allowClear value={this.state.companyId}>
                            {this.factorySelect}
                        </Select>
                        <Search style={{width: 200, marginLeft: 30}}
                                placeholder="请输入"
                                onChange={this.inputChange} allowClear value={this.state.mmName}
                        />
                        <Button icon={"search"} type='primary' style={{marginLeft: 30}}
                                onClick={this.onclickSearch.bind(this)}>搜索</Button>
                        <Button style={{marginLeft: 30}} onClick={this.onclickReset.bind(this)}>重置</Button>
                    </Col>
                    <Col span={6} className="btnRight">
                        <Button icon={"save"} type='primary' onClick={this.addmaterial.bind(this)}>新增物资</Button>
                        <Button shape='circle' type='primary' icon="download" onClick={this.exportData}/>
                    </Col>
                </Row>
                <Row style={{margin: 30}}>
                    <Table
                        columns={this.columns}
                        dataSource={this.state.data}
                        scroll={{x: 'max-content'}} // 加上这条  横向滚动  支持此属性的浏览器内容就不会换行了
                        columns={this.columns.map(item => { // 通过配置 给每个单元格添加不换行属性
                            const fun = () => ({style: {whiteSpace: 'nowrap'}});
                            item.onHeaderCell = fun;
                            item.onCell = fun;
                            return item;
                        })}
                        pagination={{
                            simple: false,
                            current: this.state.pageNum,
                            total: this.state.total,
                            pageSize: this.state.pageSize,
                            showTotal: (count = this.state.total) => {
                                return '共' + count + '条'
                            },
                            onChange: (current, pageSize) => {
                                this.onBaseClick(current, pageSize)
                            }
                        }}
                    />
                </Row>
                <Model data={this.state.modelData} handleCancel={this.handleCancel} refresh={this.refresh}
                       onRef={this.onRef} history={this.props.history}/>
            </div>
        )
    }
}

export default MaterialMaintenance